<?php

App::uses('AppController', 'Controller');
App::uses('Area', 'Model');
App::uses('Line', 'Model');
App::uses('Moe', 'Model');
App::uses('Workstation', 'Model');
App::uses('WorkstationConfig', 'Model');
App::uses('CertificationDetail', 'Model');
App::uses('Certification', 'Model');
App::uses('Shift', 'Model');
App::uses('User', 'Model');
App::uses('UserArea', 'Model');
App::uses('Attempt', 'Model');
App::uses('Evaluation', 'Model');
App::uses('EvaluationDetail', 'Model');
App::uses('Theme', 'Model');
App::uses('TeamUser', 'Model');
App::uses('Test', 'Model');

class Dg6Controller extends AppController
{
    private $lines = array();
    private $lineId = '54c81d40-4dc4-4b6e-86d8-04341b09678d';

    public function beforeFilter()
    {
        $this->Auth->allow();
        $this->loadModel('Area');
        $this->loadModel('Line');
        $this->loadModel('Moe');
        $this->loadModel('Shift');
        $this->loadModel('User');
        $this->loadModel('TeamUser');
        $this->loadModel('UserLine');
        $this->loadModel('Workstation');
        $this->loadModel('WorkstationConfig');
        $this->loadModel('CertificationDetail');
        $this->loadModel('Certification');
        $this->loadModel('Attempt');
        $this->loadModel('Evaluation');
        $this->loadModel('EvaluationDetail');
        $this->loadModel('Theme');
        $this->loadModel('UserArea');
        $this->loadModel('Link');
        $this->loadModel('Test');
        parent::beforeFilter();
    }

    public function index()
    {
        set_time_limit(360000);
        $this->request->allowMethod('get');
        $path = APP . WEBROOT_DIR . "/files/cih.csv";
        $handle = @fopen($path, "r");
        if ($handle) {
            $i = 0;
            while (($buffer = fgets($handle)) !== false) {
                $i++;
                $parts = explode(',', $buffer);
                $u = $this->User->getByNomina(trim($parts[1]));
                if (isset($u['User']) === false) {
                    continue;
                }
                $usr = $u['User'];
                $this->admissionDate($usr, trim($parts[4]));
                $usrLine = array();
                $usrLine['assign_date'] = '"' . $usr['admission_date'] . '"';
                $usrLine['days'] = $usr['days'];
                $this->level($usrLine, $usr, trim($parts[10]));
                $this->log('----' . $usr['nomina'] . '----' . $i);
                $this->UserLine->updateUserLine($usrLine, $usr['id'], $this->lineId);
                //// CERTIFICACIONES
                $n = 'Ensamble de magneto';
                $this->certification($n, $usr, $parts, 196);
                $n = 'Tester y Estampado';
                $this->certification($n, $usr, $parts, 205);
                $n = 'Moldeado de bobina';
                $this->certification($n, $usr, $parts, 214);
                $n = 'Bobinado';
                $this->certification($n, $usr, $parts, 223);
                $n = 'Ensamble de terminales';
                $this->certification($n, $usr, $parts, 232);
                $n = 'Dobles de terminales';
                $this->certification($n, $usr, $parts, 241);
                $n = 'Soldado por inmersion';
                $this->certification($n, $usr, $parts, 250);
                $n = 'Sobremoldeo';
                $this->certification($n, $usr, $parts, 259);
                $n = 'Fresado';
                $this->certification($n, $usr, $parts, 268);
                $n = 'Soldado por reistencia/de cable con bobina';
                $this->certification($n, $usr, $parts, 277);
                $n = 'Magnetizado';
                $this->certification($n, $usr, $parts, 286);
                $n = 'Inspeccion final de Componentes y empaque';
                $this->certification($n, $usr, $parts, 295);
            }
            fclose($handle);
        }
        //$this->redirect(array('controller' => 'Moe3', 'action' => 'index'));
        $this->set('title', __('Migracion MOE2 CIH DG6'));
        $this->layout = 'base';
    }

    public function admissionDate(&$user, $value)
    {
        $admissionDate = null;
        $currentDate = new DateTime();
        $user['days'] = 0;
        try {
            $dt = DateTime::createFromFormat('d/m/Y', $value);
            $interval = $currentDate->diff($dt, true);
            $admissionDate = $dt->format('Y-m-d');
            $user['days'] = $interval->format('%a');
        } catch (Exception $exc) {
            $this->log($user['nomina'] . ' FECHA DE INGRESO ERRONEA ' . $value);
        }
        $user['admission_date'] = $admissionDate;
    }

    public function level(&$usrLine, $usr, $value)
    {
        $nameLevel = trim(strtolower($value));
        $level = null;
        switch ($nameLevel) {
            case '':
            case 'nada':
                $level = 'ea9c81b9-aab7-11e4-98c8-24b6fdfa405b';
                break;
            case 'inicial':
                $level = 'eaa36449-aab7-11e4-98c8-24b6fdfa405b';
                break;
            case 'intermedio':
                $level = 'eaa36a82-aab7-11e4-98c8-24b6fdfa405b';
                break;
            case 'avanzado':
                $level = 'eaa35c69-aab7-11e4-98c8-24b6fdfa405b';
                break;
            default:
                $this->log($usr['nomina'] . ' NIVEL ERRONEO ' . $value);
                break;
        }
        $usrLine['level_excel'] = '"' . $level . '"';
    }

    public function certification($workstationName, $user, $parts, $i)
    {
        $workstation = $this->Workstation->getByLineAndDescription($this->lineId, $workstationName);
        $workstationId = $workstation['Workstation']['id'];
        $ec = trim($parts[$i + 1]);
        $ef = trim($parts[$i + 2]);
        $vc = trim($parts[$i + 3]);
        $vf = trim($parts[$i + 4]);
        $cc = trim($parts[$i + 5]);
        $cf = trim($parts[$i + 6]);
        $gc = trim($parts[$i + 7]);
        if ($ec === '' && $vc === '' && ($gc === '' || $gc === null) && ($cc === '' || $cc === null)) {
            return;
        }
        $this->Workstation->id = $workstationId;
        $w = $this->Workstation->read();
        $certificationId = String::uuid();
        $certificationData = array(
            'id' => $certificationId,
            'user_id' => $user['id'],
            'workstation_id' => $workstationId,
        );
        $this->Certification->save($certificationData);
        $this->Certification->clear();
        $def = null;
        $dcf = null;
        $dvf = null;
        if ($ec != '') {
            $ec = str_replace(',', '.', $ec);
            try {
                $def = DateTime::createFromFormat('d/m/Y', $ef);
                if ($def === false)
                    $def = null;
                else {
                    $def = $def->format('Y-m-d');
                }
                if (is_numeric($ec) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Evaluación en piso');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$ec,
                        'certification_date' => $def,
                        'status' => 1,
                    );
                    $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Evaluación CALIFICACION ERRONEA ' . $ec;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' Evaluación FECHA ERRONEA ' . $ef;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($vc != '') {
            $vc = str_replace(',', '.', $vc);
            try {
                $dvf = DateTime::createFromFormat('d/m/Y', $vf);
                if ($dvf === false)
                    $dvf = null;
                else {
                    $dvf = $dvf->format('Y-m-d');
                }
                if (is_numeric($vc) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Validación en piso');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$vc,
                        'certification_date' => $dvf,
                        'status' => 1,
                    );
                    $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Validación CALIFICACION ERRONEA ' . $vc;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' validación FECHA ERRONEA ' . $vf;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($cc != '') {
            $cc = str_replace(',', '.', $cc);
            try {
                $dcf = DateTime::createFromFormat('d/m/Y', $cf);
                if ($dcf === false)
                    $dcf = null;
                else {
                    $dcf = $dcf->format('Y-m-d');
                }
                if (is_numeric($cc) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Certificación en piso');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$cc,
                        'certification_date' => $dcf,
                        'status' => 1,
                    );
                    $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Certificación CALIFICACION ERRONEA ' . $cc;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' Certificación FECHA ERRONEA ' . $vf;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($gc != '') {
            $gc = str_replace(',', '.', $gc);
            try {
                $dcf = DateTime::createFromFormat('d/m/Y', $cf);
                if ($dcf === false)
                    $dcf = null;
                else {
                    $dcf = $dcf->format('Y-m-d');
                }
                if (is_numeric($gc) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Generales');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$gc,
                        'certification_date' => $dcf,
                        'status' => 1,
                    );
                    $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Generales CALIFICACION ERRONEA ' . $gc;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' Generales FECHA ERRONEA ' . $vf;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($def || $dvf || $dcf) {
            $a = array();
            if ($def !== null) {
                $a[] = $def;
            }
            if ($dvf !== null) {
                $a[] = $dvf;
            }
            if ($dcf !== null) {
                $a[] = $dcf;
            }
            usort($a, function ($d, $d2) {
                return $d > $d2;
            });
            $s = $a[0];
            $x = end($a);
            $l = new DateTime($x);
            $l->add(new DateInterval('P' . $w['Workstation']['life'] . 'D'));
            $this->Certification->id = $certificationId;
            $certificationData = array();
            $certificationData['start'] = $s;
            $certificationData['life'] = $l->format('Y-m-d');
            $certificationData['end'] = $x;
            $this->Certification->save($certificationData);
            $this->Certification->clear();
        }
    }

    public function nomina(&$user, $value)
    {
        if (is_numeric($value) === true) {
            if (strlen($value) != 8) {
                $this->log($user['nomina'] . ' NOMINA MAL ' . $value);
            }
        } else {
            $patron = '/^EXT[0-9]{4}/';
            $filter = preg_match($patron, $value);
            if ($filter !== 1) {
                $user['is_external'] = User::EXTERNAL_ON;
                $this->log($user['nomina'] . ' NOMINA MAL ' . $value);
            }
        }
        $value = $value == '' ? null : $value;
        $user['nomina'] = $value;
        $user['us3r'] = $value === null ? 'Temp' . rand(1, 10000) : $value;
    }

//    public function area(&$user, $value) {
//        $areaId = null;
//        try {
//            if (isset($this->areas[$value]) === false) {
//                $area = $this->Area->getByName($value);
//                if (isset($area['Area']) === true) {
//                    $this->areas[$value] = $area;
//                }
//            }
//            if (isset($this->areas[$value]) === true) {
//                $areaId = $this->areas[$value]['Area']['id'];
//            }
//        } catch (Exception $exc) {
//            var_dump($user['nomina'] . ' AREA ERRONEA: ' . $value);
//        }
//        $user['area_id'] = $areaId;
//    }

    public function name(&$user, $value)
    {
        $len = strlen($value);
        if ($len < 10) {
            $this->log($user['nomina'] . ' NOMBRE MUY CORTO ' . $value);
        }
        $user['full_name'] = utf8_encode($value);
    }

//    public function moe(&$user, $value) {
//        $moeId = null;
//        if (isset($this->moes[$value]) === false) {
//            $this->moes[$value] = $this->Moe->getByName($value);
//        }
//        if (isset($this->moes[$value]['Moe']) === true) {
//            $moeId = $this->moes[$value]['Moe']['id'];
//        } else {
//            var_dump($user['nomina'] . ' MOE ERRONEO: ' . $value);
//        }
//        $user['moe_id'] = $moeId;
//    }
//    public function shift(&$user, $value) {
//        $shiftId = null;
//        if (isset($this->shifts[$value]) === false) {
//            $this->shifts[$value] = $this->Shift->getByName($value);
//        }
//        if (isset($this->shifts[$value]['Shift']) === true) {
//            $shiftId = $this->shifts[$value]['Shift']['id'];
//        } else {
//            switch (mb_strtoupper($value)) {
//                case 'I':
//                    $user['status'] = User::STATUS_INCAPACIDAD;
//                    break;
//                case 'S':
//                    $user['support'] = User::SUPPORT_ON;
//                    break;
//            }
//            var_dump($user['nomina'] . ' TURNO ERRONEO: ' . $value);
//        }
//        $user['shift_id'] = $shiftId;
//    }

    public function curp(&$user, $value)
    {
        $len = strlen($value);
        if ($len < 18) {
            $this->log($user['nomina'] . ' CURP ERRONEA ' . $value);
            $value = null;
        }
        $user['curp'] = $value;
        $user['p4ss'] = $value === null ? 'temporal' : $value;
    }

    public function line(&$user, $value)
    {
        $lineId = null;
        if (isset($this->lines[$value]) === false) {
            $this->lines[$value] = $this->Line->getByName($value);
        }
        if (isset($this->lines[$value]['Line']) === true) {
            $lineId = $this->lines[$value]['Line']['id'];
        } else {
            switch (mb_strtoupper($value)) {
//                case 'NUEVO INGRESO':
//                    $user['status'] = User::STATUS_NEW;
//                    break;
                case 'SOPORTE':
                    $user['support'] = User::SUPPORT_ON;
                    break;
                case 'FX':
                    $user['shift_id'] = 'c7e01477-f801-11e3-9113-fc4dd44a2aac'; // Turno flexible
                    break;
            }
            var_dump($user['nomina'] . ' LINEA ERRONEA: ' . $value);
        }
        $user['line_id'] = $lineId;
    }

    public function evaluacion($testName, $usr, $t1, $t2, $t3, $t4, $aq1, $ad1, $aq2, $ad2, $aq3, $ad3)
    {
        $test = $this->Test->getByNameAndLine($testName, $this->lineId);
        $testId = $test['Test']['id'];
        if ($t1 !== null)
            $t1 = trim($t1);
        if ($t2 !== null)
            $t2 = trim($t2);
        if ($t3 !== null)
            $t3 = trim($t3);
        if ($t4 !== null)
            $t4 = trim($t4);
        if ($t1 === '' && $t2 === '' && $t3 === '' && $t4 === '') {
            return;
        }
        $evaluationId = String::uuid();
        $evaluationData = array(
            'id' => $evaluationId,
            'user_id' => $usr['id'],
            'test_id' => $testId,
            'start' => null,
            'end' => null,
            'life' => null,
            'status' => 1,
            'success' => 0,
            'training' => 0,
        );
        $this->Evaluation->save($evaluationData);
        $this->Evaluation->clear();
        if ($t1 != null) {
            $t1 = strtolower($t1) === 'ok' ? 100 : 0;
            $this->addTheme($t1, $evaluationId, $testId, 0);
        }
        if ($t2 != null) {
            $t2 = strtolower($t2) === 'ok' ? 100 : 0;
            $this->addTheme($t2, $evaluationId, $testId, 1);
        }
        if ($t3 != null) {
            $t3 = strtolower($t3) === 'ok' ? 100 : 0;
            $this->addTheme($t3, $evaluationId, $testId, 2);
        }
        if ($t4 != null) {
            $t4 = strtolower($t4) === 'ok' ? 100 : 0;
            $this->addTheme($t4, $evaluationId, $testId, 3);
        }
        $this->addAttempt($evaluationId, $aq1, $ad1, $usr, $testName);
        $this->addAttempt($evaluationId, $aq2, $ad2, $usr, $testName);
        $this->addAttempt($evaluationId, $aq3, $ad3, $usr, $testName);
    }

    private function addTheme($t1, $evaluationId, $testId, $i)
    {
        $theme = $this->Theme->getByTestAndOrden($testId, $i);
        $detailData = array(
            'id' => String::uuid(),
            'theme_id' => $theme['Theme']['id'],
            'evaluation_id' => $evaluationId,
            'qualification' => $t1,
            'evaluation_date' => null, // Desconocemos la fecha cuando se evaluo
        );
        $this->EvaluationDetail->save($detailData);
        $this->EvaluationDetail->clear();
    }

    private function addAttempt($evaluationId, $cal, $date, $usr, $testName)
    {
        $cal = str_replace(',', '.', $cal);
        if ($cal === null)
            return;
        $cal = trim($cal);
        if ($cal === '')
            return;
        if (is_numeric($cal) === true) {
            $d = DateTime::createFromFormat('d/m/Y', $date);
            $attemptData = array(
                'id' => String::uuid(),
                'evaluation_id' => $evaluationId,
                'application_date' => $d ? $d->format('Y-m-d') : null,
                'qualification' => (double)$cal,
                'status' => 1,
            );
            if ($attemptData['application_date'] === null) {
                $msg = $usr['nomina'] . ' ' . $testName . ' FECHA ERRONEA ' . $date;
                $this->log($msg, LOG_ERR);
            }
            $this->Attempt->save($attemptData);
            $this->Attempt->clear();
        } else {
            $msg = $usr['nomina'] . ' ' . $testName . ' CALIFICACION ERRONEA ' . $cal;
            $this->log($msg, LOG_ERR);
        }
    }

}
